package net.maku.generator.controller;

import cn.hutool.core.io.IoUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.maku.generator.common.page.PageResult;
import net.maku.generator.common.query.Query;
import net.maku.generator.common.utils.Result;
import net.maku.generator.config.StorageConfig;
import net.maku.generator.entity.GenTemplateTreeEntity;
import net.maku.generator.service.FileZipService;
import net.maku.generator.service.GenTemplateTreeService;
import net.maku.generator.utils.EntityCommUtils;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.util.Arrays;
import java.util.List;

/**
 * 代码模板树管理
 *
 * @author 代码小子 codeboy@126.com
 * @since 1.0.0 2024-11-09
 */
@Slf4j
@RestController
@RequestMapping("gen/gen_template_tree")
@AllArgsConstructor
public class GenTemplateTreeController {

    private final GenTemplateTreeService genTemplateTreeService;
    private final FileZipService fileZipService;

    @Resource
    private StorageConfig storageConfig;

    @GetMapping("list")
    public Result<List<GenTemplateTreeEntity>> list() {
        List<GenTemplateTreeEntity> list = genTemplateTreeService.getList();

        return Result.ok(list);
    }

    @GetMapping("page")
    public Result<PageResult<GenTemplateTreeEntity>> page(Query query){
        PageResult<GenTemplateTreeEntity> page = genTemplateTreeService.page(query);

        return Result.ok(page);
    }

    @GetMapping("{id}")
    public Result<GenTemplateTreeEntity> get(@PathVariable("id") Long id){
        GenTemplateTreeEntity entity = genTemplateTreeService.getById(id);

        // 获取上级模板名称
        if (entity.getPid() != null) {
            GenTemplateTreeEntity parentEntity = genTemplateTreeService.getById(entity.getPid());
            entity.setParentName(parentEntity.getTemplateName());
        }

        log.info("******* load readMe.md content beginning ********");
        String mdFilePath = storageConfig.generateRealFilePath(entity.getReadmeFile());
        String readmeContent = EntityCommUtils.readMdContent(mdFilePath);
        entity.setReadmeContent(readmeContent);
        log.info("******* load readMe.md content ending ********");

        return Result.ok(entity);
    }

    @PostMapping
    public Result<String> save(@RequestBody GenTemplateTreeEntity entity){
        // 预处理数据对象
        EntityCommUtils.preprecessEntity(entity);

        // 保存MD文件内容，解压模板文件
        processAttachment(entity);

        // 保存数据对象
        genTemplateTreeService.save(entity);
        return Result.ok();
    }

    @PutMapping
    public Result<String> update(@RequestBody GenTemplateTreeEntity entity){

        // 保存MD文件内容，解压模板文件
        processAttachment(entity);
        genTemplateTreeService.updateById(entity);

        return Result.ok();
    }

    @DeleteMapping
    public Result<String> delete(@RequestBody Long[] ids){
        genTemplateTreeService.removeBatchByIds(Arrays.asList(ids));
        /**
         * Todo
         * 1.删除Image文件
         * 2.删除BaseLine文件
         * 3.删除MD文件
         * 4.删除子记录
         */

        return Result.ok();
    }

    @PostMapping("nameList")
    public Result<List<String>> nameList(@RequestBody List<Long> idList) {
        List<String> list = genTemplateTreeService.getNameList(idList);

        return Result.ok(list);
    }

    /**
     * 生成代码（zip压缩包）
     */
    @GetMapping("download")
    public void download(String templateId, HttpServletResponse response) throws Exception {
        GenTemplateTreeEntity entity = genTemplateTreeService.getById(Long.parseLong(templateId));
        String templateName = entity.getTemplateName();

        // zip压缩包数据
        String templateZip = entity.getTemplateZip();
        String templateZipPath = storageConfig.generateRealFilePath(templateZip);
        byte[] data = IoUtil.readBytes(new FileInputStream(templateZipPath));

        String downloadName = EntityCommUtils.generateDownloadName();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadName + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), false, data);
    }

    /**
     * 保存MD文件内容，解压模板文件
     * @param entity
     */
    private void processAttachment(GenTemplateTreeEntity entity){
        // 保存MD内容
        String mdFilePath = storageConfig.generateRealFilePath(entity.getReadmeFile());
        EntityCommUtils.writeMdContent(mdFilePath, entity.getReadmeContent());

        // 解压缩模板，并保存模板路径
        String zipSourcePath = storageConfig.generateRealFilePath(entity.getTemplateZip());
        String zipTargetPath = storageConfig.generateRealTemplatePath(entity.getTemplateZip());
        String templatePath = storageConfig.generateRelevantTemplatePath(entity.getTemplateZip());

        fileZipService.unzipFile(zipSourcePath, zipTargetPath);
        entity.setTemplatePath(templatePath);
    }

}